<template>
  <div class="app-container">
        <!-- 查询条件 -->
    <div class="filter-container" style="margin-bottom: 20px;">
      <!-- 查询输入框 -->
      <el-input
        v-model="queryParams.title"
        placeholder="标题"
        clearable
        style="width: 200px; margin-right: 10px;"
        @keyup.enter.native="handleQuery"
        @clear="handleQuery"
      />
      <el-button
        type="primary"
        icon="el-icon-search"
        @click="handleQuery"
      >
        查询
      </el-button>
      
      <!-- 添加按钮 -->
      <el-button 
        class="filter-item" 
        type="primary" 
        icon="el-icon-plus" 
        style="margin-left: 10px;"
        @click="handleCreate"
      >
        添加Banner
      </el-button>
    </div>

    <!-- 表格 - 添加卡片阴影和边距 -->
    <el-card shadow="never" style="margin-bottom: 20px;">
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="序号" width="80" align="center">
          <template slot-scope="scope">
            {{ (page - 1) * limit + scope.$index + 1 }}
          </template>
        </el-table-column>
        
        <el-table-column label="标题" prop="title" align="center" />
        
        <el-table-column label="图片" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.imageUrl" style="height: 50px;">
          </template>
        </el-table-column>
        
        <el-table-column label="链接地址" prop="linkUrl" align="center" />
        
        <el-table-column label="排序" prop="sort" width="100" align="center" />
        
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 - 固定在底部右侧 -->
    <div class="pagination-container" style="text-align: center; margin-top: 20px;">
      <el-pagination
        :current-page="page"
        :page-sizes="[5, 10, 20]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form ref="bannerForm" :model="temp" label-position="right" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        
        <el-form-item label="轮播图片">
          <el-upload
            class="cover-uploader"
            :action="BASE_API+'/eduoss/fileoss'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="temp.imageUrl" :src="temp.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div style="margin-top: 10px; color: #999;">建议尺寸：1920×500像素，支持JPG/PNG格式</div>
        </el-form-item>
        
        <el-form-item label="链接地址">
          <el-input v-model="temp.linkUrl" placeholder="将自动根据图片URL生成" />
        </el-form-item>
        
        <el-form-item label="排序">
          <el-input-number v-model="temp.sort" :min="0" />
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import bannerApi from '@/api/admin/banner'


export default {
  data() {
    return {
      list: null,
      total: 0,
      page: 1,
      limit: 10,
      listLoading: true,
      BASE_API: process.env.BASE_API,

      queryParams: {
        title: ''
      },
      
      temp: {
        id: '',
        title: '',
        imageUrl: '',
        linkUrl: '',
        sort: 0
      },
      
      dialogVisible: false,
      dialogStatus: '',
      dialogTitle: ''
    }
  },
  
  created() {
    this.getList()
  },
  
  methods: {
    getList() {
      this.listLoading = true
      bannerApi.getBannerList(this.page, this.limit, this.queryParams)
        .then(response => {
          this.list = response.data.items
          this.total = response.data.total
          this.listLoading = false
        })
    },

    handleQuery() {
      this.page = 1 // 重置页码
      this.getList()
    },
    
    handleSizeChange(val) {
      this.limit = val
      this.getList()
    },
    
    handleCurrentChange(val) {
      this.page = val
      this.getList()
    },
    
    resetTemp() {
      this.temp = {
        id: '',
        title: '',
        imageUrl: '',
        linkUrl: '',
        sort: 0
      }
    },
    
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogTitle = '添加Banner'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['bannerForm'].clearValidate()
      })
    },
    
    createData() {
      this.$refs['bannerForm'].validate((valid) => {
        if (!valid) return;
      
        if (!this.temp.imageUrl) {
          this.$message.error('请上传轮播图片');
          return;
        }
      
        console.log('提交的数据:', JSON.stringify(this.temp)); // 调试用
      
        bannerApi.addBanner(this.temp)
          .then(response => {
            console.log('添加成功响应:', response); // 调试用
            this.dialogVisible = false;
            this.$message.success('添加成功');
            this.getList();
          })
          .catch(error => {
            console.error('添加失败:', error); // 调试用
            this.$message.error('添加失败: ' + (error.message || '未知错误'));
          });
      });
    },
    
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // 复制对象
      this.dialogStatus = 'update'
      this.dialogTitle = '编辑Banner'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['bannerForm'].clearValidate()
      })
    },
    
    updateData() {
      this.$refs['bannerForm'].validate((valid) => {
        if (!valid) return;
      
        if (!this.temp.imageUrl) {
          this.$message.error('请上传轮播图片');
          return;
        }
      
        bannerApi.updateBanner(this.temp)
          .then(() => {
            this.dialogVisible = false;
            this.$message.success('更新成功');
            this.getList();
          })
          .catch(error => {
            this.$message.error('更新失败: ' + error.message);
          });
      });
    },
    
    handleDelete(row) {
      this.$confirm('确认删除该Banner吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        bannerApi.deleteBanner(row.id)
          .then(() => {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getList()
          })
      })
    },
    
    handleAvatarSuccess(res, file) {
      console.log('上传成功响应:', res); // 调试用
      if (res && res.data && res.data.url) {
        this.temp.imageUrl = res.data.url;
        this.autoFillLinkUrl(res.data.url);
        this.$message.success('图片上传成功');
        this.$forceUpdate(); // 强制更新视图
      } else {
        this.$message.error('获取图片URL失败');
      }
    },
    
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    autoFillLinkUrl(imageUrl){
      if (this.temp.linkUrl && this.temp.linkUrl.trim() !== '') {
        return;
      }
      const fileName = imageUrl.split('/').pop();
      this.temp.linkUrl = `${this.BASE_API}/banner/redirect/${fileName}`;
    }
  }
}
</script>

<style scoped>
.cover-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 100%;
  height: 200px;
  display: block;
  object-fit: contain;
}
.filter-container {
  padding: 20px 0;
  display: flex;
  align-items: center;
}

.filter-container {
  padding: 20px 0;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.pagination-container {
  padding: 20px 0;
}

/* 表格卡片样式 */
.el-card {
  border-radius: 4px;
}
</style>